package com.hmall.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1)  // 确保它优先执行
@Component
public class AuthorizeFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取当前请求的 headers
        HttpHeaders headers = exchange.getRequest().getHeaders();

        // 创建一个新的可变 HttpHeaders 实例
        HttpHeaders mutableHeaders = new HttpHeaders();
        mutableHeaders.addAll(headers); // 复制原始头部

        // 添加 Authorization 请求头
        mutableHeaders.add("Authorization", "2");

        // 创建新的请求并应用修改后的 headers
        ServerWebExchange modifiedExchange = exchange.mutate()
                .request(exchange.getRequest().mutate()
                        .headers(httpHeaders -> {
                            httpHeaders.clear(); // 清空原有头部
                            httpHeaders.addAll(mutableHeaders); // 添加修改后的头部
                        })
                        .build())
                .build();

        // 传递给下游过滤器
        return chain.filter(modifiedExchange);
    }
}
